<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    protected $table = 'admin_roles';

    public $fillable = [
        'name',
        'description'
    ];

    /**
     * [permissions 权限]
     * @return [type] [description]
     */
    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'admin_permission_role', 'role_id', 'permission_id');
    }

    /**
     * [dictionarys 字典]
     * @return [type] [description]
     */
    public function dictionarys()
    {
        return $this->belongsToMany(Dictionary::class, 'admin_dictionary_role', 'role_id', 'dictionary_id');
    }

    /**
     * [users 用户]
     * @return [type] [description]
     */
    public function users()
    {
        return $this->belongsToMany(AdminUser::class, 'admin_role_user', 'role_id', 'user_id');
    }

    /**
     * [groups 组]
     * @return [type] [description]
     */
    public function groups() {
        return $this->belongsToMany(Group::class, 'admin_group_role', 'role_id', 'group_id');
    }


    //给角色添加权限
    public function givePermissionTo($permission)
    {
        return $this->permissions()->save($permission);
    }

    //角色权限整体添加与修改
    public function givePermissionsTo(array $permissionId)
    {
        $this->permissions()->detach();
        $permissions = Permission::whereIn('id', $permissionId)->get();
        foreach ($permissions as $v) {
            $this->givePermissionTo($v);
        }
        return true;
    }

}
